package com.admin.model;

import java.util.List;

import com.admin.util.Page;
import com.admin.util.UtilTools;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IDataSourceProvider;
import com.jfinal.plugin.activerecord.Model;

public class MyDB<M extends Model<?>> extends Model<M> {
	
	public String tableName;
	
	public static ActiveRecordPlugin loadTableConfig(IDataSourceProvider cp){
		ActiveRecordPlugin arp = new ActiveRecordPlugin(cp);
		arp.addMapping("sys_function", Sys_Function.class);
		arp.addMapping("sys_role_function", RoleFunction.class);
		arp.addMapping("sys_roles", Roles.class);
		arp.addMapping("sys_users", Sys_User.class);
		arp.addMapping("sys_boot_screen", SysBootScreen.class);
		arp.addMapping("sys_dict", SysDict.class);
		arp.addMapping("sys_dict_item", SysDictItem.class);
		arp.addMapping("sys_article",Article.class);
		arp.addMapping("orders",Orders.class);
		arp.addMapping("orders_return",OrdersReturn.class);
		arp.addMapping("orders_source",OrdersSource.class);
		return arp;
	}
	
	/**
	 * 查询数据集合
	 * @param table 表名
	 * @param params 查询条件需带上字段，如:"id=1"
	 * @param sorts 排序字段
	 * @param sortTypes 排序方式，长度要与sorts的长度保持一致，否则排序就全部默认为升序
	 * @return
	 */
	public List<M> find(String[] params, String[] sorts,String[] sortTypes) {
		try {
			StringBuffer sql = new StringBuffer();
			sql.append("select * from ");
			sql.append(tableName);
			sql.append(" where 1=1");
			if(null != params){
				for (String param : params) {
					if(null != param){
						sql.append(" and " + param);
					}
				}
			}
			if(null != sorts){
				sql.append(" order by ");
				for(int i = 0; i< sorts.length;i++){
					sql.append(sorts[i]);
					// 如果排序方式与排序字段数量不一致，就默认都为升序，防止报错
					if(null != sortTypes && sortTypes.length == sorts.length){
						sql.append(" "+sortTypes[i]);
					}
					sql.append(",");
				}
				System.out.println(sql.substring(0,sql.length()-1).toString());
				return find(sql.substring(0,sql.length()-1).toString());
			}
			System.out.println(sql.toString());
			return find(sql.toString());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 按照where查询
	 * @param where
	 * @return
	 */
	public List<M> query(String[] where) {
		StringBuffer sql = new StringBuffer();
		sql.append("select * from ");
		sql.append(tableName);
		sql.append(" where 1=1");
		if(null != where){
			for (String w : where) {
				if(null != w){
					sql.append(" and " + w);					
				}
			}
		}
		System.out.println(sql.toString());
		return find(sql.toString());
	}
	
	/**
	 * 查询总条数
	 * @return
	 */
	public long getCount(String[] params){
		StringBuffer sql = new StringBuffer();
		sql.append("select count(*) count from " + tableName +" where 1 = 1 ");
		if(null != params){
			for (String param : params) {
				if(null != param){
					sql.append(" and " + param);
				}
			}
		}
		return find(sql.toString()).get(0).getLong("count");
	}
	
	/**
	 * 查询单个实体
	 * @param where
	 * @return
	 */
	public M queryModel(String[] where) {
		StringBuffer sql = new StringBuffer();
		sql.append("select * from ");
		sql.append(tableName);
		sql.append(" where 1=1");
		if(null != where){
			for (String w : where) {
				if(null != w){
					sql.append(" and " + w);					
				}
			}
		}
		return findFirst(sql.toString());
	}
	
	/**
	 * 查询总条数
	 * @return
	 */
	public long getCount(String sql){
		return find(sql).get(0).getLong("count");
	}
	
	/**
	 * 分页查询
	 * @param params
	 * @param page
	 */
	public void listByPage(String[] params,Page<M> page){
		page.setTotalCount(getCount(params));
		List<M> list = query(params,page);
		page.setResult(list);
	}
	
	/**
	 * 分页查询结果集
	 * @param where
	 * @param start
	 * @param size
	 * @return
	 */
	public List<M> query(String[] where,Page<M> page) {
		StringBuffer sql = new StringBuffer();
		sql.append("select * from ");
		sql.append(tableName);
		sql.append(" where 1=1");
		if(null != where){
			for (String w : where) {
				if(null != w){
					sql.append(" and " + w);					
				}
			}
		}
		if(UtilTools.isNotNull(page.getOrderField())){
			sql.append(" order by "+ page.getOrderField() +" "+ page.getOrderDirection());
		}
		sql.append(" limit "+ page.getStartIndex() +","+page.getPageSize());
		System.out.println(sql.toString());
		return find(sql.toString());
		
	}
	
	/**
	 * 逻辑删除或者恢复
	 * @param id
	 */
	public void LogicDel(Integer id) {
		M m = findById(id);
		if (m.getInt("del") == 0) {
			findById(id).set("del", "1").update();
		} else {
			findById(id).set("del", "0").update();
		}
	}
	
	/**
	 * 删除
	 * @param id
	 */
	public boolean Del(Integer id) {
		M m = findById(id);
		if (m != null) {
			m.delete();
			return true;
		}
		return false;
	}
	
	/**
	 * 修改
	 * @param set
	 * @param id
	 * @return
	 */
	public boolean update(List<String[]> set, Integer id) {
		M m = findById(id);
		if (m != null) {
			for (int i = 0; i < set.size(); i++) {
				m.set(set.get(i)[0], set.get(i)[0]);
			}
			m.update();
			return true;
		}
		return false;
	}
	
	/**
	 * 保存
	 * @param set
	 * @return
	 */
	public boolean save(List<String[]> set){
		this.clear();
		for (int i = 0; i < set.size(); i++) {
			this.set(set.get(i)[0], set.get(i)[0]);
		}
		return this.save();
	}
	
	/**
	 * 通过sql操作
	 * @param sql
	 * @return
	 */
	public boolean operateBySql(String sql){
		try {
			Db.update(sql);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 根据主键id批量删除
	 * @param ids
	 * @return
	 */
	public boolean del(String[] ids){
		String sql = "delete from "+ tableName +" where id in ("+ UtilTools.getStr(ids) +")";
		return this.operateBySql(sql);
	}
	
	/**
	 * 根据主键id批量假删除  修改订单状态为0
	 * @param ids
	 * @return
	 */
	public boolean jiadel(String[] ids){
		String sql = "update "+ tableName +" set status = 0 where id in ("+ UtilTools.getStr(ids) +")";
		return this.operateBySql(sql);
	}
	
	// 查看详情
	public M getObject(Long id){
		List<M> list = this.query(new String[]{"id="+id});
		if(null != list && list.size() > 0){
			return list.get(0);
		}
		return null;
	}
}
